/**
 * 标签路由模块
 * @author HalRui
 * @version 1.0.0
 * @description 定义标签相关的API接口，包括标签创建、查询、更新、删除、搜索、统计、使用量管理等功能
 * @date 2025年9月27日
 */

const express = require('express');
const router = express.Router();
const tagsApi = require('../../api/tags-api');

/**
 * 创建标签
 * POST /tags/create
 */
router.post('/create', async (req, res) => {
    try {
        const {
            name,
            description,
            category,
            color,
            icon,
            isOfficial,
            createdBy
        } = req.body;
        
        // 参数验证
        if (!name || name.trim().length === 0) {
            return res.status(400).json({
                success: false,
                message: '标签名称不能为空'
            });
        }
        
        if (name.trim().length > 50) {
            return res.status(400).json({
                success: false,
                message: '标签名称不能超过50个字符'
            });
        }
        
        // 验证分类
        const validCategories = [
            'general', 'genre', 'mood', 'topic', 'style', 
            'language', 'difficulty', 'duration', 'quality', 'custom'
        ];
        if (category && !validCategories.includes(category)) {
            return res.status(400).json({
                success: false,
                message: '无效的标签分类'
            });
        }
        
        // 验证颜色格式
        if (color && !/^#[0-9A-Fa-f]{6}$/.test(color)) {
            return res.status(400).json({
                success: false,
                message: '颜色格式无效，请使用十六进制格式（如：#007bff）'
            });
        }
        
        const tagData = {
            name: name.trim(),
            description: description || '',
            category: category || 'general',
            color: color || '#007bff',
            icon: icon || '',
            isOfficial: isOfficial || false,
            createdBy: createdBy ? parseInt(createdBy) : null
        };
        
        const result = await tagsApi.createTag(tagData);
        
        if (result.success) {
            res.status(201).json(result);
        } else {
            res.status(400).json(result);
        }
    } catch (error) {
        console.error('创建标签接口错误:', error);
        res.status(500).json({
            success: false,
            message: '服务器内部错误'
        });
    }
});

/**
 * 获取标签列表
 * GET /tags/list
 */
router.get('/list', async (req, res) => {
    try {
        const {
            category,
            isOfficial,
            isActive,
            keyword,
            sortBy = 'usageCount',
            sortOrder = 'desc',
            page = 1,
            limit = 20
        } = req.query;
        
        const pageNum = parseInt(page);
        const limitNum = parseInt(limit);
        
        // 参数验证
        if (pageNum < 1 || limitNum < 1 || limitNum > 100) {
            return res.status(400).json({
                success: false,
                message: '无效的分页参数'
            });
        }
        
        // 验证排序字段
        const validSortFields = ['usageCount', 'createAt', 'name', 'updateAt'];
        if (!validSortFields.includes(sortBy)) {
            return res.status(400).json({
                success: false,
                message: '无效的排序字段'
            });
        }
        
        const options = {
            page: pageNum,
            limit: limitNum,
            sortBy,
            sortOrder
        };
        
        if (category) options.category = category;
        if (isOfficial !== undefined) options.isOfficial = isOfficial === 'true';
        if (isActive !== undefined) options.isActive = isActive === 'true';
        if (keyword) options.keyword = keyword.trim();
        
        const result = await tagsApi.getTagList(options);
        
        if (result.success) {
            res.json(result);
        } else {
            res.status(400).json(result);
        }
    } catch (error) {
        console.error('获取标签列表接口错误:', error);
        res.status(500).json({
            success: false,
            message: '服务器内部错误'
        });
    }
});

/**
 * 获取标签详情
 * GET /tags/detail/:tagId
 */
router.get('/detail/:tagId', async (req, res) => {
    try {
        const { tagId } = req.params;
        
        // 参数验证
        if (!tagId || isNaN(parseInt(tagId))) {
            return res.status(400).json({
                success: false,
                message: '无效的标签ID'
            });
        }
        
        const result = await tagsApi.getTagDetail(parseInt(tagId));
        
        if (result.success) {
            res.json(result);
        } else {
            res.status(404).json(result);
        }
    } catch (error) {
        console.error('获取标签详情接口错误:', error);
        res.status(500).json({
            success: false,
            message: '服务器内部错误'
        });
    }
});

/**
 * 更新标签
 * PUT /tags/update/:tagId
 */
router.put('/update/:tagId', async (req, res) => {
    try {
        const { tagId } = req.params;
        const { name, description, category, color, icon, isActive, userId } = req.body;
        
        // 参数验证
        if (!tagId || isNaN(parseInt(tagId))) {
            return res.status(400).json({
                success: false,
                message: '无效的标签ID'
            });
        }
        
        if (!userId || isNaN(parseInt(userId))) {
            return res.status(400).json({
                success: false,
                message: '缺少用户ID'
            });
        }
        
        // 验证标签名称
        if (name && (name.trim().length === 0 || name.trim().length > 50)) {
            return res.status(400).json({
                success: false,
                message: '标签名称长度必须在1-50个字符之间'
            });
        }
        
        // 验证颜色格式
        if (color && !/^#[0-9A-Fa-f]{6}$/.test(color)) {
            return res.status(400).json({
                success: false,
                message: '颜色格式无效，请使用十六进制格式（如：#007bff）'
            });
        }
        
        const updateData = {};
        if (name) updateData.name = name.trim();
        if (description !== undefined) updateData.description = description;
        if (category) updateData.category = category;
        if (color) updateData.color = color;
        if (icon !== undefined) updateData.icon = icon;
        if (isActive !== undefined) updateData.isActive = isActive;
        
        const result = await tagsApi.updateTag(parseInt(tagId), updateData, parseInt(userId));
        
        if (result.success) {
            res.json(result);
        } else {
            res.status(400).json(result);
        }
    } catch (error) {
        console.error('更新标签接口错误:', error);
        res.status(500).json({
            success: false,
            message: '服务器内部错误'
        });
    }
});

/**
 * 删除标签
 * DELETE /tags/delete/:tagId
 */
router.delete('/delete/:tagId', async (req, res) => {
    try {
        const { tagId } = req.params;
        const { userId } = req.body;
        
        // 参数验证
        if (!tagId || isNaN(parseInt(tagId))) {
            return res.status(400).json({
                success: false,
                message: '无效的标签ID'
            });
        }
        
        if (!userId || isNaN(parseInt(userId))) {
            return res.status(400).json({
                success: false,
                message: '缺少用户ID'
            });
        }
        
        const result = await tagsApi.deleteTag(parseInt(tagId), parseInt(userId));
        
        if (result.success) {
            res.json(result);
        } else {
            res.status(400).json(result);
        }
    } catch (error) {
        console.error('删除标签接口错误:', error);
        res.status(500).json({
            success: false,
            message: '服务器内部错误'
        });
    }
});

/**
 * 批量获取标签信息
 * POST /tags/batch-get
 */
router.post('/batch-get', async (req, res) => {
    try {
        const { tagIds } = req.body;
        
        // 参数验证
        if (!tagIds || !Array.isArray(tagIds) || tagIds.length === 0) {
            return res.status(400).json({
                success: false,
                message: '标签ID列表不能为空'
            });
        }
        
        if (tagIds.length > 100) {
            return res.status(400).json({
                success: false,
                message: '一次最多查询100个标签'
            });
        }
        
        // 验证所有ID都是数字
        const validTagIds = tagIds.filter(id => !isNaN(parseInt(id))).map(id => parseInt(id));
        if (validTagIds.length === 0) {
            return res.status(400).json({
                success: false,
                message: '没有有效的标签ID'
            });
        }
        
        const result = await tagsApi.getTagsByIds(validTagIds);
        
        if (result.success) {
            res.json(result);
        } else {
            res.status(400).json(result);
        }
    } catch (error) {
        console.error('批量获取标签信息接口错误:', error);
        res.status(500).json({
            success: false,
            message: '服务器内部错误'
        });
    }
});

/**
 * 获取热门标签
 * GET /tags/popular
 */
router.get('/popular', async (req, res) => {
    try {
        const {
            category,
            limit = 10,
            minUsageCount = 1
        } = req.query;
        
        const limitNum = parseInt(limit);
        const minUsage = parseInt(minUsageCount);
        
        // 参数验证
        if (limitNum < 1 || limitNum > 50) {
            return res.status(400).json({
                success: false,
                message: '限制数量必须在1-50之间'
            });
        }
        
        if (minUsage < 0) {
            return res.status(400).json({
                success: false,
                message: '最小使用次数不能为负数'
            });
        }
        
        const options = {
            limit: limitNum,
            minUsageCount: minUsage
        };
        
        if (category) options.category = category;
        
        const result = await tagsApi.getPopularTags(options);
        
        if (result.success) {
            res.json(result);
        } else {
            res.status(400).json(result);
        }
    } catch (error) {
        console.error('获取热门标签接口错误:', error);
        res.status(500).json({
            success: false,
            message: '服务器内部错误'
        });
    }
});

/**
 * 获取标签统计信息
 * GET /tags/stats
 */
router.get('/stats', async (req, res) => {
    try {
        const result = await tagsApi.getTagStats();
        
        if (result.success) {
            res.json(result);
        } else {
            res.status(400).json(result);
        }
    } catch (error) {
        console.error('获取标签统计接口错误:', error);
        res.status(500).json({
            success: false,
            message: '服务器内部错误'
        });
    }
});

/**
 * 搜索标签
 * GET /tags/search
 */
router.get('/search', async (req, res) => {
    try {
        const {
            keyword,
            category,
            limit = 20,
            exactMatch = false
        } = req.query;
        
        // 参数验证
        if (!keyword || keyword.trim().length === 0) {
            return res.status(400).json({
                success: false,
                message: '搜索关键词不能为空'
            });
        }
        
        const limitNum = parseInt(limit);
        if (limitNum < 1 || limitNum > 50) {
            return res.status(400).json({
                success: false,
                message: '限制数量必须在1-50之间'
            });
        }
        
        const options = {
            keyword: keyword.trim(),
            limit: limitNum,
            exactMatch: exactMatch === 'true'
        };
        
        if (category) options.category = category;
        
        const result = await tagsApi.searchTags(options);
        
        if (result.success) {
            res.json(result);
        } else {
            res.status(400).json(result);
        }
    } catch (error) {
        console.error('搜索标签接口错误:', error);
        res.status(500).json({
            success: false,
            message: '服务器内部错误'
        });
    }
});

/**
 * 增加标签使用次数
 * PUT /tags/increase-usage/:tagId
 */
router.put('/increase-usage/:tagId', async (req, res) => {
    try {
        const { tagId } = req.params;
        const { count = 1 } = req.body;
        
        // 参数验证
        if (!tagId || isNaN(parseInt(tagId))) {
            return res.status(400).json({
                success: false,
                message: '无效的标签ID'
            });
        }
        
        const countNum = parseInt(count);
        if (countNum < 1 || countNum > 1000) {
            return res.status(400).json({
                success: false,
                message: '增加数量必须在1-1000之间'
            });
        }
        
        const result = await tagsApi.increaseTagUsage(parseInt(tagId), countNum);
        
        if (result.success) {
            res.json(result);
        } else {
            res.status(400).json(result);
        }
    } catch (error) {
        console.error('增加标签使用次数接口错误:', error);
        res.status(500).json({
            success: false,
            message: '服务器内部错误'
        });
    }
});

/**
 * 减少标签使用次数
 * PUT /tags/decrease-usage/:tagId
 */
router.put('/decrease-usage/:tagId', async (req, res) => {
    try {
        const { tagId } = req.params;
        const { count = 1 } = req.body;
        
        // 参数验证
        if (!tagId || isNaN(parseInt(tagId))) {
            return res.status(400).json({
                success: false,
                message: '无效的标签ID'
            });
        }
        
        const countNum = parseInt(count);
        if (countNum < 1 || countNum > 1000) {
            return res.status(400).json({
                success: false,
                message: '减少数量必须在1-1000之间'
            });
        }
        
        const result = await tagsApi.decreaseTagUsage(parseInt(tagId), countNum);
        
        if (result.success) {
            res.json(result);
        } else {
            res.status(400).json(result);
        }
    } catch (error) {
        console.error('减少标签使用次数接口错误:', error);
        res.status(500).json({
            success: false,
            message: '服务器内部错误'
        });
    }
});

/**
 * 激活标签
 * PUT /tags/activate/:tagId
 */
router.put('/activate/:tagId', async (req, res) => {
    try {
        const { tagId } = req.params;
        const { userId } = req.body;
        
        // 参数验证
        if (!tagId || isNaN(parseInt(tagId))) {
            return res.status(400).json({
                success: false,
                message: '无效的标签ID'
            });
        }
        
        if (!userId || isNaN(parseInt(userId))) {
            return res.status(400).json({
                success: false,
                message: '缺少用户ID'
            });
        }
        
        const result = await tagsApi.activateTag(parseInt(tagId), parseInt(userId));
        
        if (result.success) {
            res.json(result);
        } else {
            res.status(400).json(result);
        }
    } catch (error) {
        console.error('激活标签接口错误:', error);
        res.status(500).json({
            success: false,
            message: '服务器内部错误'
        });
    }
});

/**
 * 停用标签
 * PUT /tags/deactivate/:tagId
 */
router.put('/deactivate/:tagId', async (req, res) => {
    try {
        const { tagId } = req.params;
        const { userId } = req.body;
        
        // 参数验证
        if (!tagId || isNaN(parseInt(tagId))) {
            return res.status(400).json({
                success: false,
                message: '无效的标签ID'
            });
        }
        
        if (!userId || isNaN(parseInt(userId))) {
            return res.status(400).json({
                success: false,
                message: '缺少用户ID'
            });
        }
        
        const result = await tagsApi.deactivateTag(parseInt(tagId), parseInt(userId));
        
        if (result.success) {
            res.json(result);
        } else {
            res.status(400).json(result);
        }
    } catch (error) {
        console.error('停用标签接口错误:', error);
        res.status(500).json({
            success: false,
            message: '服务器内部错误'
        });
    }
});

/**
 * 获取标签分类列表
 * GET /tags/categories
 */
router.get('/categories', async (req, res) => {
    try {
        const result = await tagsApi.getTagCategories();
        
        if (result.success) {
            res.json(result);
        } else {
            res.status(400).json(result);
        }
    } catch (error) {
        console.error('获取标签分类接口错误:', error);
        res.status(500).json({
            success: false,
            message: '服务器内部错误'
        });
    }
});

module.exports = router;